﻿using System;
using System.IO;
using System.Text;

namespace NazTek.Extension.Clr4
{
    /// <summary>
    /// Extends System.IO.Stream
    /// </summary>
    public static class StreamExtension
    {
        /// <summary> 
        /// Flushes the content of a <see cref="Stream"/> to a base 32 string
        /// </summary> 
        /// <param name="sourceStream">The stream to extract string data from</param> 
        /// <param name="encoding">Encodes the string with</param>
        /// <returns>A string representation of the stream</returns> 
        /// <remarks></remarks> 
        /// <example><code>string s = myStream.ToString(Encoding.Default)</code></example>
        public static string ToString(this Stream sourceStream, Encoding encoding)
        {
            Parameter.Validate<Encoding>("encoding", encoding);

            // convert the byte array into a string 
            return encoding.GetString(sourceStream.ToByteArray());
        }
        /// <summary>
        /// Flushes the content of a <see cref="Stream"/> to a byte array
        /// </summary>
        /// <param name="sourceStream">The stream to extract content from</param>
        /// <returns>The byte array representation of the stream</returns>
        /// <example><code>byte[] bytes = myStream.ToByteArray()</code></example>
        public static byte[] ToByteArray(this Stream sourceStream)
        {
            // read the stream into a byte array 
            int objectLength = Convert.ToInt32(sourceStream.Length);
            byte[] objectBytes = new byte[objectLength];
            sourceStream.Position = 0;
            sourceStream.Read(objectBytes, 0, objectLength);
            return objectBytes;
        }
    }
}
